//店铺设置弹窗
import { Input, Select } from "@/views/components/PrefixPlaceholder";
import { CommonModal } from "@/views/components/CommonModal";
import SubTitle from "@/pages/OrderModule/common/components/SubTitle";
import { useAnchor } from "@/pages/OrderModule/common/hooks/useAnchor";
import { message, Form, Tabs, Tooltip, Radio, Alert, Space, Popover, InputNumber, Tag, Button, Drawer } from "antd";
import { useEffect, useRef, useState, useMemo } from "react";
import FormRowWrapper from "./FormRowWrapper";
import CommonLoading from "@/components/CommonLoading";
import { getSendAddress, newEcStoreSettingDetail, updateNewEcStoreSetting, querySnapshot, storeAuthClosed, getTableDataOp } from "../service";
import { isEmpty, isNil } from "lodash";
import Style from "./index.module.less";
import IconFont from "@/components/IconFont";
import CommonImgsLoad from "@/components/CommonImgsLoad";
import moment from "moment";
import { useNavigate } from "react-router-dom";
import CloseStoreModal from "./CloseStoreModal";
import AuthorizeStoreModal from "../components/AuthorizeStore";
import InventoryTipModal from "./InventoryTipModal";
import CommonDrawer from '@/components/CommonDrawer';

const { Option } = Select;

//tab
const formCategoryList = [
	{
		key: "basicInfo",
		title: "基础信息",
		render(node) {
			return (
				<div id={this.key}>
					<SubTitle title={this.title} as="s2" symbol />
					{node}
				</div>
			);
		}
	},
	{
		key: "authorizeInfo",
		title: "授权信息",
		render(node) {
			return (
				<div id={this.key}>
					<SubTitle title={this.title} as="s2" symbol />
					{node}
				</div>
			);
		}
	},
	{
		key: "deliveryInfo",
		title: "发货信息",
		render(node) {
			return (
				<div id={this.key}>
					<SubTitle title={<>{this.title}</>} as="s2" symbol />
					{node}
				</div>
			);
		}
	},
	{
		key: "switchSettings",
		title: "开关设置",
		render(node) {
			return (
				<div id={this.key}>
					<SubTitle title={this.title} as="s2" symbol />
					{node}
				</div>
			);
		}
	}
];

//状态
const storeStateMap = {
	1: "正常",
	2: "已到期",
	3: "已关闭",
	4: "授权失效"
};

const nowTime = Date.now();

const StoreSettingModal = ({ visible, type, recordData, handleCancel, handleOk }) => {
	const [tab, setTab] = useState(formCategoryList[0].key);
	const formWrapperRef = useRef(null);
	const anchorItems = useRef({});
	const { currentAnchor, scrollToAnchor } = useAnchor(formWrapperRef, anchorItems);
	const [detailData, setDetailData] = useState({}); //详情数据
	const [list, setList] = useState([]); //寄件地址信息
	const [showTimeInput, setShowTimeInput] = useState(false); //展示时间input输入
	const [lastId, setLastId] = useState(null); //快照上一个
	const [nextId, setNextId] = useState(null); //快照下一个
	const [loading, setLoading] = useState(false);
	const [clseVisible, setClseVisible] = useState(false); //关闭店铺弹窗提示
	const [authorizeVisible, setAuthorizeVisible] = useState(false); //授权权限
	const [inventoryVisible, setInventoryVisible] = useState(false); //修改库存同步提示
	const [inventoryType, setinventoryType] = useState(false); //修改库存同步开关开闭还是开启
	const [inventoryVal, setInventoryVal] = useState({}); //修改库存同步的值
	const [changeColumnKeys, setchangeColumnKeys] = useState([]); //快照改动的字段
	//京东店铺需要选择京东云仓的店铺
	const [yunCangList, setYunCangList] = useState([]);
	const [form] = Form.useForm();
	const navigate = useNavigate();

	useEffect(() => {
		if (visible) {
			getSendList();
			form.resetFields();
			if(recordData.type == 1) {
				//请求云仓店铺数据
				queryYunCangList();
			}
			if (!isEmpty(recordData)) {
				if (type == "edit") {
					getDetailData();
				} else {
					getViewData(recordData.id);
				}
			}
		}
	}, [visible, recordData, type]);

	useEffect(() => {
		if (visible) {
			formCategoryList.forEach(item => {
				anchorItems.current[item.key] = document.getElementById(item.key);
			});
		}
	}, [visible]);

	useEffect(() => {
		if (currentAnchor) {
			setTab(currentAnchor);
		}
	}, [currentAnchor]);

	useEffect(() => {
		if (!isEmpty(detailData)) {
			form.resetFields();
		}
	}, [detailData]);

	//获取详情数据(编辑)
	const getDetailData = async () => {
		setLoading(true);
		setDetailData({});
		const { data = {}, success } = await newEcStoreSettingDetail({
			storePk: recordData.id
		});
		if (success) {
			setShowTimeInput(data.autoBackflow == 4);
			setInventoryVal({ syncStockType: data.syncStockType });
			setDetailData(data);
		}
		setLoading(false);
	};

	//获取详情数据(快照)
	const getViewData = async id => {
		setLoading(true);
		setDetailData({});
		const { data = {}, success } = await querySnapshot({
			id
		});
		if (success) {
			const { lastId, nextId, operationSnapshot = {}, changeColumnKeys = [] } = data;
			setShowTimeInput(operationSnapshot.autoBackflow == 4);
			setDetailData(operationSnapshot);
			setLastId(lastId);
			setNextId(nextId);
			setchangeColumnKeys(changeColumnKeys);
			if(operationSnapshot.type == 1) {
				//请求云仓店铺数据
				queryYunCangList();
			}
		}
		setLoading(false);
	};

	//获取云仓列表数据
	const queryYunCangList = async () => {
		const params = {
			type: 19,
			size: 100,
			current: 1
		};
		const { data, success } = await getTableDataOp(params);
		if (success) {
			const { records = [] } = data || {};
			setYunCangList(records);
		}
	};

	//获取寄件地址下拉
	const getSendList = async () => {
		const { data = [], success } = await getSendAddress();
		if (success) {
			setList(data);
		}
	};

	//修改店铺设置
	const handleSaveStoreConfig = async val => {
		setLoading(true);
		let res;
		const params = {
			...val,
			id: recordData.id,
			syncStockType: inventoryVal.syncStockType
		};
		res = await updateNewEcStoreSetting(params);
		const { success, msg = "" } = res;
		if (success) {
			message.success(msg);
			handleOk();
		}
		setLoading(false);
	};

	const onFinish = () => {
		form
			.validateFields()
			.then(val => {
				handleSaveStoreConfig(val);
			})
			.catch(err => {});
	};
	const onFinishFailed = errorInfo => {
		console.log("Failed:", errorInfo);
	};
	const handleCreditImgUpload = val => {
		form.setFieldsValue({ goodCreditImage: val });
	};

	const handlePicInfoImgUpload = val => {
		form.setFieldsValue({ picInfoImage: val });
	};

	//点击物流回传
	const handleRadioChange = e => {
		setShowTimeInput(e.target.value == 4);
	};

	//公共跳转逻辑
	const publicHandleClick = pathname => {
		navigate(pathname);
	};

	//关闭店铺
	const closeShop = async () => {
		setLoading(true);
		const { success } = await storeAuthClosed({
			id: detailData.id
		});
		setLoading(false);
		if (success) {
			message.success("关闭成功");
			setClseVisible(false);
		}
	};

	//切换库存设置
	const handleSwitchSyncStock = e => {
		const val = e.target.value;
		setInventoryVisible(true);
		setinventoryType(val == 1);
	};

	//快照key是否修改打上标识
	const showmarkCode = code => {
		if (changeColumnKeys.includes(code)) {
			return true;
		}
		return false;
	};

	//问号图标内容展示
	const PopoverRender = (content, style={}) => {
		return (
			<Popover content={<div style={{ width: "200px"}}>{content}</div>}>
				<div style={style}>
					<IconFont type="iconwenhao1" />
				</div>
			</Popover>
		);
	};

	//底部按钮渲染
	const footerRender = () => {
		if (type == "edit") {
			return (
				<div className={Style.footer}>
					<Button style={{ marginRight: "16px" }} onClick={() => handleCancel()}>
						取消
					</Button>
					<Button
						onClick={() => {
							form.submit();
						}}
						type="primary"
					>
						确认
					</Button>
				</div>
			);
		} else {
			return (
				<div className={Style.footer}>
					{lastId ? (
						<Button
							onClick={() => {
								getViewData(lastId);
							}}
						>
							上一条
						</Button>
					) : (
						""
					)}
					{nextId ? (
						<Button
							onClick={() => {
								getViewData(nextId);
							}}
						>
							下一条
						</Button>
					) : (
						""
					)}
					<Button onClick={() => handleCancel()}>关闭</Button>
				</div>
			);
		}
	};

	//寄件地址
	const addressOptions = list.map(d => (
		<Option key={d.id} value={d.id} label={d.address}>
			<Tooltip title={d.address}>{d.address}</Tooltip>
		</Option>
	));

	//京东云仓列表
	const yunCangOptions = yunCangList.map(d => (
		<Option key={d.id} value={d.id} label={d.storeName}>
			<Tooltip title={d.storeName}>{d.storeName}</Tooltip>
		</Option>
	));

	//关闭授权店铺提示
	const CloseStoreModalProps = {
		visible: clseVisible,
		handleCancel() {
			setClseVisible(false);
		},
		handleOk() {
			closeShop();
		}
	};

	//店铺授权
	const AuthorizeStoreModalProps = {
		visible: authorizeVisible,
		handleCancel() {
			setAuthorizeVisible(false);
		}
	};

	//库存修改提示
	const InventoryTipModalProps = {
		visible: inventoryVisible,
		inventoryType,
		item: detailData,
		handleCancel() {
			setInventoryVisible(false);
			form.setFieldsValue({
				isSyncStock: detailData.isSyncStock
			});
		},
		handleOk(val) {
			setInventoryVisible(false);
			setInventoryVal(val);
		}
	};

	return (
		<CommonDrawer
			title="店铺设置"
			open={visible}
			onClose={handleCancel}
			onOk={() => {
				form.submit();
			}}
			footer={footerRender()}
			width="70%"
			okText="保存"
		>
			<div className={Style["modal-content"]}>
				{type != "edit" ? (
					<Alert
						style={{ marginBottom: "16px" }}
						showIcon
						message={"下方颜色标记的是上次与上上次对比内容有变更的项，未有颜色标注的代表本次没做修改"}
					/>
				) : (
					""
				)}
				<div style={{ display: "flex", marginBottom: "24px" }}>
					<div>{detailData?.systemStoreName}</div>
					<Tag style={{ marginLeft: "8px", marginRight: "14px" }} color="cyan">
						{storeStateMap[detailData.storeState]}
					</Tag>
					{type == "edit" && detailData.storeState == 4 ? (
						""
					) : (
						<span>{moment(detailData.authExpireTime * 1000).format("YYYY-MM-DD HH:mm:ss")}</span>
					)}
					{nowTime < detailData.authExpireTime * 1000 ? <span className="common-color9">授权过期</span> : ""}
					{type == "edit" ? (
						<>
							{detailData.storeState != 1 ? (
								<Button
									onClick={() => {
										setAuthorizeVisible(true);
									}}
									style={{ marginLeft: "20px" }}
									type="link"
								>
									重新授权
								</Button>
							) : (
								""
							)}
							{detailData.storeState != 3 ? (
								<Button
									onClick={() => {
										setClseVisible(true);
									}}
									type="link"
								>
									关闭店铺
								</Button>
							) : (
								""
							)}
						</>
					) : (
						""
					)}
					<div style={{ marginLeft: "auto" }}>
						<img className={Style.platformImg} src={detailData.image} />
						<span>{detailData.erpPlatformName}</span>
					</div>
				</div>
				<div className={Style.archor_tab + " rule-reset"}>
					<Tabs
						activeKey={tab}
						onChange={val => {
							scrollToAnchor(val);
						}}
					>
						{formCategoryList.map(item => (!(item.key == 'switchSettings' && (recordData.type == 19 || detailData.type == 19))) && (
							<Tabs.TabPane tab={item.title} key={item.key}></Tabs.TabPane>
						))}
					</Tabs>
				</div>
				<div ref={formWrapperRef} className={Style["modal-form"]}>
					<Form
						form={form}
						initialValues={{
							...detailData,
							isSync: detailData?.isSync || 0,
							isSyncStock: detailData?.isSyncStock || 0
						}}
						onFinish={onFinish}
						onFinishFailed={onFinishFailed}
						autoComplete="off"
						layout="horizontal"
						labelAlign="right"
					>
						{formCategoryList[0].render()}
						{FormRowWrapper([
							<Form.Item
								className={showmarkCode("systemStoreName") ? Style.highInput : ""}
								name="systemStoreName"
								// rules={[{ required: true, message: "必填，请输入店铺名称" }]}
							>
								<Input disabled={type != "edit"} placeholder="店铺" maxLength={100} showCount />
							</Form.Item>,
							<Form.Item className={showmarkCode("storeIntro") ? Style.highInput : ""} name="storeIntro">
								<Input disabled={type != "edit"} placeholder="店铺简称" maxLength={64} showCount />
							</Form.Item>
						])}
						{FormRowWrapper([
							<Form.Item
								name="picInfoImage"
								label={<span className={showmarkCode("picInfoImage") ? "common-color13" : ""}>吊牌</span>}
							>
								<CommonImgsLoad antPreview={true} disabled={type != "edit"} handleOk={handlePicInfoImgUpload} img={detailData.picInfoImage} />
							</Form.Item>,
							<Form.Item
							name="goodCreditImage"
							label={<span className={showmarkCode("goodCreditImage") ? "common-color13" : ""}>吊牌2</span>}
						>
							<CommonImgsLoad antPreview={true} disabled={type != "edit"} handleOk={handleCreditImgUpload} img={detailData.goodCreditImage} />
						</Form.Item>
						])}

						{formCategoryList[1].render()}
						{FormRowWrapper([
							<Form.Item className={Style.disabledInput} name="storeName">
								<Input disabled placeholder="平台店铺" />
							</Form.Item>,
							<Form.Item className={showmarkCode("storeWebUrl") ? Style.highInput : ""} name="storeWebUrl">
								<Input disabled={type != "edit"} placeholder="店铺网址" maxLength={250} />
							</Form.Item>,
							(recordData.type == 19 || detailData.type == 19) ? <Form.Item className={showmarkCode("jdExpressCode") ? Style.highInput : ""} name="jdExpressCode">
								<Input disabled={type != "edit"} placeholder="事业部编码" maxLength={50} />
							</Form.Item> : null,
							(recordData.type == 1 || detailData.type == 1) ? <div style={{ position: 'relative'}}><Form.Item className={showmarkCode("jdYcId") ? Style.highInput : ""} name="jdYcId">
								<Select disabled={type != "edit"} showSearch placeholder="请选择京东云仓" allowClear={true}>
									{yunCangOptions}
								</Select>
							</Form.Item>
							{PopoverRender(
									<div>
										<div>注释</div>
										<div>1、如果京东店铺含有京东云仓订单（即需要通过云仓发货），则支持选择已授权的云仓和事业部编码。</div>
										<div>2、订单页面，可以通过对应云仓获取运单号。包括直接获取运单号、导入云仓运单号、云仓单号匹配3种方式</div>
									</div>
								, { position: 'absolute', right: '-20px', top: 0 })}</div> : null
						])}
						{formCategoryList[2].render()}
						{FormRowWrapper([
							<Form.Item className={showmarkCode("userAddressId") ? Style.highInput : ""} name="userAddressId">
								<Select disabled={type != "edit"} showSearch placeholder="寄件信息" allowClear={true}>
									{addressOptions}
								</Select>
							</Form.Item>,
							<Button onClick={() => publicHandleClick("/account/sendAddress")} type="link">
								前往设置
							</Button>
						])}
					 <div style={{ height: (recordData.type == 19 || detailData.type == 19) ? 0 : 'auto', overflow: 'hidden' }}>
							{formCategoryList[3].render()}
							<p style={{ marginTop: "16px", marginBottom: "12px" }}>订单设置</p>
							<Form.Item
								style={{ marginLeft: "60px" }}
								name="isSync"
								label={<span className={showmarkCode("isSync") ? "common-color13" : ""}>同步三方订单和商品数据</span>}
							>
								<Radio.Group disabled={type != "edit"}>
									<Radio value={1}>开启</Radio>
									<Radio value={0}>
										<div style={{ display: "flex" }}>
											关闭
											{PopoverRender("请先设置系统商品自动同步规则后开启")}
										</div>
									</Radio>
								</Radio.Group>
							</Form.Item>
							<p style={{ marginTop: "16px", marginBottom: "12px" }}>库存设置</p>
							<Form.Item
								style={{ marginLeft: "60px" }}
								name="isSyncStock"
								label={<span className={showmarkCode("isSyncStock") ? "common-color13" : ""}>库存自动同步</span>}
							>
								<Radio.Group onChange={e => handleSwitchSyncStock(e)} disabled={type != "edit"}>
									<Radio value={1}>开启</Radio>
									<Radio value={0}>
										<div style={{ display: "flex" }}>
											关闭
											{PopoverRender(
												"自动上传库存 (ERP同步库存信息至平台，ERP库存发生变动时触发同步)。不需要同步的商品请在商品资料中禁止库存同步。并且注意库存数量，防止下架！"
											)}
										</div>
									</Radio>
								</Radio.Group>
							</Form.Item>
							<p style={{ marginTop: "16px", marginBottom: "12px" }}>售后设置</p>
							<Form.Item
								style={{ marginLeft: "60px" }}
								name="isSyncAfterSalesOrder"
								label={<span className={showmarkCode("isSyncAfterSalesOrder") ? "common-color13" : ""}>同步平台售后单</span>}
							>
								<Radio.Group disabled={type != "edit"}>
									<Radio value={1}>开启</Radio>
									<Radio value={0}>关闭</Radio>
								</Radio.Group>
							</Form.Item>
							<p style={{ marginTop: "16px", marginBottom: "12px" }}>物流回传设置</p>
							<Form.Item
								style={{ marginLeft: "60px" }}
								label={<span className={showmarkCode("autoBackflow") ? "common-color13" : ""}>物流回传</span>}
							>
								<Form.Item name="autoBackflow" label=" " colon={false}>
									<Radio.Group disabled={type != "edit"} onChange={handleRadioChange}>
										<Space direction="vertical">
											<Radio value={0}>默认回传(发货后回传)</Radio>
											<Radio value={1}>
												<div style={{ display: "flex" }}>
													立即回传(生成单号即回传)
													{PopoverRender("使用立即回传所造成后果需自己承担，请谨慎选择")}
												</div>
											</Radio>
											<div style={{ display: "flex" }}>
												按平台发货时效回传{PopoverRender("目前只有拼多多、抖音、快手会返回最晚发货时间。其他平台都不会返回")}
											</div>
											<Radio value={2}>包装后回传(订单商品包装完成后回传,自发打印的订单会在打印后上传)</Radio>
											<Radio value={3}>
												<span style={{ lineHeight: "18px" }}>备货后回传(拿货商品全部备货或者无采购入库后触发回传，库存商品</span>
												<p style={{ lineHeight: "18px", textIndent: "24px" }}>会直接回传)</p>
											</Radio>
											<Radio value={4}>
												<div style={{ display: "flex" }}>
													按平台发货时效回传{PopoverRender("目前只有拼多多、抖音、快手会返回最晚发货时间。其他平台都不会返回")}
												</div>
											</Radio>
										</Space>
									</Radio.Group>
								</Form.Item>
								{showTimeInput ? (
									<>
										<Form.Item label=" " colon={false}>
											<Form.Item
												label={
													<span className="lable-require">
														<span className={showmarkCode("inAdvanceBackflowTime") ? "common-color13" : ""}>最晚发货时间</span>
													</span>
												}
											>
												<div style={{ display: "flex" }}>
													<span style={{ marginRight: "8px" }}>提前</span>
													<Form.Item
														name="inAdvanceBackflowTime"
														rules={[
															{
																pattern: /^[1-9]\d*$/g,
																message: "请输入正整数"
															},
															{
																required: true,
																message: "时间不能为空"
															}
														]}
													>
														<InputNumber disabled={type != "edit"} min={1} max={9999} style={{ width: "100px" }}></InputNumber>
													</Form.Item>
													<span style={{ marginLeft: "8px" }}>小时</span>
													{PopoverRender("若平台订单有返回“最晚发货时间”，则优先按照“最晚发货时间 - 设置的时间”进行回传")}
												</div>
											</Form.Item>
											<Form.Item
												label={
													<span className="lable-require">
														<span className={showmarkCode("customBackflowTime") ? "common-color13" : ""}>自定义回传时间</span>
													</span>
												}
											>
												<div style={{ display: "flex" }}>
													<Form.Item
														name="customBackflowTime"
														rules={[
															{
																pattern: /^[1-9]\d*$/g,
																message: "请输入正整数"
															},
															{
																required: true,
																message: "时间不能为空"
															}
														]}
													>
														<InputNumber disabled={type != "edit"} min={1} max={9999} style={{ width: "100px" }}></InputNumber>
													</Form.Item>
													<span style={{ marginLeft: "8px" }}>小时</span>
													{PopoverRender("若平台订单没有返回最晚发货时间，则按照订单“平台付款时间+设置的时间”回传")}
												</div>
											</Form.Item>
										</Form.Item>
									</>
								) : (
									""
								)}
							</Form.Item>
						</div>
					</Form>
				</div>
			</div>
			<CloseStoreModal {...CloseStoreModalProps} />
			<AuthorizeStoreModal {...AuthorizeStoreModalProps} />
			<InventoryTipModal {...InventoryTipModalProps} />
			<CommonLoading loading={loading} />
		</CommonDrawer>
	);
};

export default StoreSettingModal;
